`

You should see output like the following:

$ ./exit_codes.sh

The status code of the ls command was: 0

The status code of the non-existing lzl command was: 127

As you can see, we received two distinct status codes, one for

each command. The first command returned 0 (success), and the

second returned 127 (command not found).

N O T E

Use /dev/null with caution. You may miss out on important errors if you

choose to redirect output to it. When in doubt, redirect standard streams

such as standard output and standard error to a dedicated log file in-

stead.

To understand why you might want to use status codes, imagine

you’re trying to download a 1GB file from the internet using bash. It

might be wise to first check if the file already exists on the

filesystem in case someone ran the script already and retrieved it.

Also, you might want to check that you have enough free space on

the disk before attempting the download. By running commands and

looking at their exit status codes, we can decide whether to proceed

with the file download.

Setting a Script’s Exit Codes

You can set the exit code of a script using the exit command,

as shown below:

#!/bin/bash

# Sets the exit code of the script to be 223

echo "Exiting with status code: 223"

exit 223

Save this script as set_status_code.sh and run it on the command

line, then use the special variable $? to see the status code it returns:

$ chmod u+x set_status_code.sh

$ ./set_status_code.sh

Exiting with status code: 223

echo $?

223

You can use the $? variable to check the exit status of a script,

but also of individual commands:

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks